package org.wei.p2p.consumer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.wei.p2p.api.account.model.AccountDTO;
import org.wei.p2p.api.account.model.AccountRegisterDTO;
import org.wei.p2p.api.consumer.model.ConsumerDTO;
import org.wei.p2p.api.consumer.model.ConsumerRegisterDTO;
import org.wei.p2p.common.domain.BusinessException;
import org.wei.p2p.common.domain.CodePrefixCode;
import org.wei.p2p.common.domain.CommonErrorCode;
import org.wei.p2p.common.domain.RestResponse;
import org.wei.p2p.common.utils.CodeNoUtil;
import org.wei.p2p.consumer.agent.AccountApiAgent;
import org.wei.p2p.consumer.common.ConsumerErrorCode;
import org.wei.p2p.consumer.entity.Consumer;
import org.wei.p2p.consumer.mapper.ConsumerMapper;
import org.wei.p2p.consumer.service.IConsumerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * c端用户信息表 服务实现类
 * </p>
 *
 * @author wei
 * @since 2022-04-24
 */
@Service
public class ConsumerServiceImpl extends ServiceImpl<ConsumerMapper, Consumer> implements IConsumerService {

    @Resource
    private AccountApiAgent accountApiAgent;

    @Override
    public Integer checkMobile(String mobile) {
        return getByMobile(mobile) != null ? 1 : 0;
    }

    /**
     * 根据手机号获取用户信息
     * @param mobile 手机号
     * @return
     */
    private ConsumerDTO getByMobile(String mobile) {
        Consumer entity = getOne(new LambdaQueryWrapper<Consumer>()
                .eq(Consumer::getMobile, mobile));
        return convertConsumerEntityToDTO(entity);
    }

    private ConsumerDTO convertConsumerEntityToDTO(Consumer entity) {
        if (entity == null) {
            return null;
        }
        ConsumerDTO dto = new ConsumerDTO();
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }

    @Override
    public void register(ConsumerRegisterDTO consumerRegisterDTO) {
        if(checkMobile(consumerRegisterDTO.getMobile())==1){
            throw new BusinessException(ConsumerErrorCode.E_140107);
        }
        Consumer consumer=new Consumer();
        BeanUtils.copyProperties(consumerRegisterDTO, consumer);
        consumer.setUsername(CodeNoUtil.getNo(CodePrefixCode.CODE_NO_PREFIX));
        consumerRegisterDTO.setUsername(consumer.getUsername());
        consumer.setUserNo(CodeNoUtil.getNo(CodePrefixCode.CODE_REQUEST_PREFIX));
        consumer.setIsBindCard(0);
        save(consumer);

        //远程调用account
        AccountRegisterDTO accountRegisterDTO=new AccountRegisterDTO();
        BeanUtils.copyProperties(consumerRegisterDTO, accountRegisterDTO);
        RestResponse<AccountDTO> restResponse=accountApiAgent.register(accountRegisterDTO);
        if(restResponse.getCode()!= CommonErrorCode.SUCCESS.getCode()){
            throw new BusinessException(ConsumerErrorCode.E_140106);
        }
    }
}
